package com.easychat.interceptor;

import com.easychat.common.LeaseException;
import com.easychat.dto.TokenUserInfoDto;
import com.easychat.entity.UserInfo;
import com.easychat.entity.constants.Constants;
import com.easychat.enums.ExceptionCodeEnum;
import com.easychat.utils.LoginUserHolder;
import com.easychat.utils.StringTools;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 10 2024/10/8
 */
@Component
public class GlobalIntercepter implements HandlerInterceptor {
     @Resource
     private RedisTemplate redisTemplate;

     @Override
     public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
          String token = request.getHeader("token");
          if(StringTools.isEmpty(token)){
               throw new LeaseException(ExceptionCodeEnum.NOT_LOG);
          }
          TokenUserInfoDto tokenUserInfoDto = (TokenUserInfoDto) redisTemplate.opsForValue().get(Constants.REDIS_KEY_WS_TOKEN + token);
          if(tokenUserInfoDto ==null || StringTools.isEmpty(tokenUserInfoDto.getUserId())){
               throw new LeaseException(ExceptionCodeEnum.NOT_LOG);
          }
          LoginUserHolder.set(tokenUserInfoDto);

          return true;
     }

     @Override
     public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
          if(LoginUserHolder.get() != null) LoginUserHolder.clear();
     }
}
